﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using ServiceEntities;
using BVCommon.Entities;
using System.Data;
using System.Collections;

// NOTE: If you change the class name "Service" here, you must also update the reference to "Service" in Web.config and in the associated .svc file.
public class ProductService : IProductService
{

    public List<Product> GetData()
    {
        List<Product> list;
        using (BtVisionEntities data = new BtVisionEntities())
        {
            list = (from p in data.Product
                   select p).ToList();
        }
        return list;
    }

    public void SaveData(IEnumerable<Product> list)
    {
        using (BtVisionEntities data = new BtVisionEntities())
        {
            IEnumerable<Product> dbList = (from p in data.Product select p).ToArray();

            //delete objects which were deleted on client
            foreach (Product item in dbList)
            {
                var identifiers = (from r in list where r.id == item.id select r);

                if (identifiers != null && identifiers.Count() ==0)
                {
                    data.DeleteObject(item);
                }
            }
            data.SaveChanges();
            
            try
            {
                foreach (Product item in list)
                {
                    var indentifiers = from p in dbList 
                                       where p.id == item.id 
                                       select p;
                    //update object
                    if (indentifiers != null && indentifiers.Count() == 1)
                    {
                        Product product = indentifiers.ElementAt(0);
                        product.name = item.name;
                        product.code = item.code;
                        product.measurement = item.measurement;
                        product.cost = item.cost;
                        product.available_quantity = item.available_quantity;
                    }
                    //insert new object
                    else 
                    {
                        data.AddToProduct(item);
                    }
                }
                data.SaveChanges();
            }
            catch (OptimisticConcurrencyException exp)
            {
                data.Refresh(System.Data.Objects.RefreshMode.ClientWins, dbList);
                data.SaveChanges();
            }

        }
    }
}
